
colWidCM = [85, 114, 174]/10; % in mm
% Axes Size
axAspectRatio = 10.5/13;
axWidth = 2.7; % This is based on playing around in illustrator quite a bit
axHeight = 3.1; % Also based on playing around in illustrator 
% Markup properties (smaller for insets!)
fontSize = 7;
lineWidth = 0.5;
markerSize = 4;




dpath = '/Users/landauland/Documents/Research/SabatiniLab/data/manuscriptPreparation/compileData';
fig4resAB = load(fullfile(dpath,'figure4resultsAB'));
res = fig4resAB.res;




%%
NR = numel(res);

cnum = [res(:).cellNum];
distance = [res(:).distance]; distance(distance<0)=-25;
eidx = [1 9 10];
pklength = 20;
bswin = 80:98;

tvec = 1:512;
sap = cell2mat({res(:).sap});
sglu = cell2mat({res(:).sglu});
sgap = cell2mat({res(:).sgap});
ssyn = cell2mat({res(:).ssyn});
dap = cell2mat({res(:).dap});

dglu = cell2mat({res(:).dglu});
dgap = cell2mat({res(:).dgap});
dsyn = cell2mat({res(:).dsyn});

spk = cell2mat({res(:).spk}'); spk = spk(:,eidx);
spk(spk<0)=0;
sbase = cell2mat({res(:).sbase}'); sbase = sbase(:,eidx); % spine Base

idxZeroSet = 99:101;
sglu(idxZeroSet,:) = repmat(sbase(:,2)',length(idxZeroSet),1);
sgap(idxZeroSet,:) = repmat(sbase(:,3)',length(idxZeroSet),1);

dpk = cell2mat({res(:).dpk}'); dpk = dpk(:,eidx);
dpk(dpk<0)=0;
dbase = cell2mat({res(:).dbase}'); dbase = dbase(:,eidx);

% calculate peak for synthetic
pwsyn = [100 150];
synpk = zeros(NR,1);
synpkidx = zeros(NR,1);
for s = 1:NR
    [~,synpkidx(s)] = max(ssyn(pwsyn(1):pwsyn(2),s));
    synpkidx(s) = synpkidx(s) + pwsyn(1) - 1;
    synpk(s) = mean(ssyn((0:pklength-1)+synpkidx(s),s));
end
synbase = mean(ssyn(bswin,:),1)';
synpk = synpk - synbase;

nl = spk(:,3)./synpk; 
ampreglu = (spk(:,3)-synpk)./abs(spk(:,2)); % (amplification - synthetic)/gluAlone
ampreap = (spk(:,3)-synpk)./abs(spk(:,1)); % (amplification - synthetic)/apAlone
lampreap = real(log(ampreap));

nlComponent = spk(:,3) - synpk;

% get physiology 
pglu = cell2mat({res(:).pglu});
ptvec = 0.1:0.1:1000;
pBaseWin = [80 98];
pPkWin = [100 120];
pbaseSample = [find(ptvec>=pBaseWin(1),1) find(ptvec>=pBaseWin(2),1)];
ppkSample = [find(ptvec>=pPkWin(1),1) find(ptvec>=pPkWin(2),1)];
pbase = mean(pglu(pbaseSample(1):pbaseSample(2),:),1);
pglubase = pglu - pbase;
ppk = mean(pglubase(ppkSample(1):ppkSample(2),:),1);
NR = size(sap,2);

saxWidth =colWidCM(3)/4;
saxHeight= colWidCM(3)/4*axAspectRatio;


% Figure 4A
tvIdx = find(tvec>=50,1):find(tvec>=400,1);
tvUse = tvec(tvIdx);
figure(1); clf; hold on; 
set(gcf,'units','centimeters','position',[40 30 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.2 0.1 axWidth*0.875 axHeight]);
shadedErrorBar(tvUse, mean(sap(tvIdx,:) - sbase(:,1)',2), std(sap(tvIdx,:),1,2)/sqrt(NR),{'color','k','linewidth',lineWidth},0);
shadedErrorBar(tvUse, mean(sglu(tvIdx,:) - sbase(:,2)',2), std(sglu(tvIdx,:),1,2)/sqrt(NR),{'color','r','linewidth',lineWidth},0);
shadedErrorBar(tvUse, mean(sgap(tvIdx,:) - sbase(:,3)',2), std(sgap(tvIdx,:),1,2)/sqrt(NR),{'color',[1,0.55,0],'linewidth',lineWidth},0);
xlim([50 400]);
ylim([-0.02 0.14]);
% Plot tick to indicate time of stimulations
line([100 100],[-0.02 -0.014],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [245 0.05 50 0.02]; %260 if supplemental
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
% Plot Legend
legPos = [378, 398, 0.121,-0.013, -5];
line(legPos([1,2]),(legPos(3)+0*legPos(4))*[1,1],'Color','k','linewidth',lineWidth);
line(legPos([1,2]),(legPos(3)+1*legPos(4))*[1,1],'Color','r','linewidth',lineWidth);
line(legPos([1,2]),(legPos(3)+2*legPos(4))*[1,1],'Color',[1,0.55,0],'linewidth',lineWidth);
text(legPos(1)+legPos(5),legPos(3)+0*legPos(4),'bAP','Fontsize',fontSize,'HorizontalAlignment','Right');
text(legPos(1)+legPos(5),legPos(3)+1*legPos(4),'uEPSP','Fontsize',fontSize,'HorizontalAlignment','Right');
text(legPos(1)+legPos(5),legPos(3)+2*legPos(4),'Pairing','Fontsize',fontSize,'HorizontalAlignment','Right');
set(gca,'visible','off');
% Label Traces w/ Schematic
spineSchematic = [80 -17 0.035 0.0075];
line(spineSchematic([1,1]),spineSchematic(3)+spineSchematic(4)*[-1,1],'color','k','linewidth',lineWidth*4);
line(spineSchematic(1)+[0 spineSchematic(2)],spineSchematic(3)*[1,1],'color','k','linewidth',lineWidth*3);
plot(spineSchematic(1)+spineSchematic(2),spineSchematic(3),'marker','.','markersize',markerSize*2.5,'color','k');
plot(spineSchematic(1)+spineSchematic(2),spineSchematic(3),'marker','.','markersize',markerSize*2,'color','r');
text(60, 0.1245, 'in NBQX','fontsize',fontSize,'HorizontalAlignment','Left');
set(gca,'visible','off');


% Figure 4B
figure(2); clf; hold on; 
set(gcf,'units','centimeters','position',[40 20 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.7 0.75 axWidth*0.725 axHeight*0.73]); % Note difference for equal axes!
setBackX = [-0.015 -0.0225 -0.0225 -0.05];
setBackY = [-0.01 -0.065 -0.09 -0.9];
plot(1:3,spk,'color',0.7*[1,1,1],'linewidth',lineWidth,'marker','.','markersize',markerSize);
plot(1:3,mean(spk,1),'color','k','linewidth',lineWidth*3,'marker','.','markersize',markerSize*3);
xLim = [0.8 3.2];
xlim(xLim + [setBackY(2) 0]);
ylim([setBackX(2) 0.25]);
line(xLim(1)+setBackY(1)*[1,1],[0 0.25],'color','k','linewidth',lineWidth);
xticks = 1:3;
xlabels = {'bAP','uEPSP','Pairing'};
for tt = 1:length(xticks)
    line(xticks(tt)*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xticks(tt),setBackX(3),xlabels{tt},'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Top','Rotation',45);
end
yticks = 0:0.1:0.2;
for t = yticks
    line(xLim(1)+setBackY([1 2]),t+[0,0],'color','k','linewidth',lineWidth);
    text(xLim(1)+setBackY(3),t,num2str(t),'fontsize',fontSize,'horizontalalignment','right','verticalAlignment','Middle');
end
text(xLim(1)+setBackY(4),0.125,'\DeltaG/R','fontsize',fontSize,'HorizontalAlignment','center','verticalAlignment','top','Rotation',90);
set(gca,'visible','off');
inset = axes('Units','Centimeters','Position',[0.9 1.75 0.9 1.0]); hold on;
plot(inset,ptvec(1:10:end), pglubase(1:10:end,:), 'color','k','linewidth',lineWidth/5);
xlim(inset,[80, 150]);
ylim(inset,[-0.5 3]);
line([100 100],[-0.5 -0.25],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [110 1.4 20 1];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),sprintf('%d mV',scalePosition(4)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');




%% == dendrite patching == 

% Properties 
colWidCM = [85, 114, 174]/10; % in mm
% Axes Size
axAspectRatio = 10.5/13;
axWidth = 2.2; % From playing around in illustrator
axHeight = 6.2/3; % Playing around in illustrator
% Markup properties (smaller for insets!)
fontSize = 7;
lineWidth = 0.5;
markerSize = 4;


dpath = '/Users/landauland/Documents/Research/SabatiniLab/data/manuscriptPreparation/compileData';
fig4resCH = load(fullfile(dpath,'figure4resultsCH'));
res = fig4resCH.res;


distance = [res(:).distance];
vcScale = 4; 
tv = 0:0.01:1000-0.01;
imtv = 1:512;
sap = [res(:).somaAP];
cAP = [res(:).cAP];
eAP = [res(:).eAP];
imap = [res(:).ap1];
imap5 = [res(:).ap5];
iFilt = 1;
bimap = imap - mean(imap(80:98,:),1);
bimap5 = imap5 - mean(imap5(80:98,:),1);
bimap = smoothsmooth(bimap,iFilt);
bimap5 = smoothsmooth(bimap5,iFilt);
pkImap = mean(bimap(107:127,:),1);
pkImap5 = mean(bimap5(137:157,:),1);
pkImap(pkImap<0)=0.005;
NR = size(cAP,2);

% remove baseline
bswin = [find(tv>=80,1) find(tv>=98,1)];
bcAP = mean(cAP(bswin(1):bswin(2),:),1);
beAP = mean(eAP(bswin(1):bswin(2),:),1);
dcap = cAP - bcAP;
deap = eAP - beAP;
dap = deap - dcap;

% compute RC check differences
rcwin = [find(tv>=875,1) find(tv>=925,1)];
rcctl = 1000*mean(dcap(rcwin(1):rcwin(2),:),1);
rcexp = 1000*mean(deap(rcwin(1):rcwin(2),:),1);

resctl = 1e-6 * rcctl*1e-6 / -50e-12; % rcctl & rcexp in µV... 
resexp = 1e-6 * rcexp*1e-6 / -50e-12; % RC Check was -50pA.. get Resistance

% Find Peak Times!
pkwin = [find(tv>=100,1) find(tv>=110,1)];
fLength = 2;
fdap = smoothsmooth(dap,fLength);

% Find peaks in dendrite and soma
[~,idxPk] = max(fdap(pkwin(1):pkwin(2),:),[],1); 
idxPk = idxPk + pkwin(1) - 1;
[~,idxSPk] = max(sap(pkwin(1):pkwin(2),:),[],1);
idxSPk = idxSPk + pkwin(1) - 1;
pkTime = [tv(idxPk); tv(idxSPk)];

% Find peak amplitude in dendrite
pkEAP = zeros(NR,1); 
for f = 1:NR
    pkEAP(f) = mean(dap(idxPk(f)-5:idxPk(f)+5,f),1); 
end

% Shift dendritic recordings
NT = size(sap,1);
shiftedSAP = zeros(size(sap));
shiftedFDAP = zeros(size(fdap));
for nr = 1:NR
    shiftFactor = idxSPk(nr)-10000-1;
    shiftedSAP(1:NT-shiftFactor,nr)=sap(shiftFactor+1:end,nr);
    shiftedFDAP(1:NT-shiftFactor,nr)=fdap(shiftFactor+1:end,nr);
end

% Get all trials
pall = {res(:).pall};

% set this up to measure different variables on each trial
maxTrial = 90;
NR = size(pall,2);


preBaseWin = [find(tv>=80,1) find(tv>=95,1)];
shelfWin = [find(tv>=105,1) find(tv>=106,1)];
postBaseWin = [find(tv>=200,1) find(tv>=300,1)];
positiveWin = [find(tv>=99,1) find(tv>=105,1)];
pkHalfWidth = 10;
negWindow = 250;
stdWin = [find(tv>=60,1) find(tv>=95,1)];
stdEachWin = find(tv>=5,1)-1;
pkFractionMax = 0.7;

rcwin = [find(tv>=875,1) find(tv>=925,1)];
rcBase = [find(tv>=800,1) find(tv>=840,1)];

% baseline, shelf, post-baseline,
% positiveAmplitude, negativeAmplitude, 
% somaPotential, singleTrialSTD(5ms-Average), RCResistance, SNR
andata = nan(maxTrial,NR,10);
andataExtra = nan(maxTrial,NR,2);
numberTrial = zeros(NR,1);
for nr = 1:NR
    shiftFactor = idxSPk(nr)-10000-1;
    cdata = pall{nr}{1,2,1};
    ctlData = pall{nr}{1,1,1};
    cdata = cdata - mean(ctlData,2); % Subtract average of control trials!
    NT = size(cdata,2);
    numberTrial(nr) = NT;
    cshd = cat(1, cdata(shiftFactor+1:end,:), nan(shiftFactor,NT));
    andata(1:NT,nr,1) = mean(cshd(preBaseWin(1):preBaseWin(2),:),1);
    andata(1:NT,nr,2) = mean(cshd(shelfWin(1):shelfWin(2),:),1);
    andata(1:NT,nr,3) = mean(cshd(postBaseWin(1):postBaseWin(2),:),1);
    % Compute std on trial by trial basis!
    % Note: there's movement over 35ms, so using the average of 5ms windows
    % is ideal for a good estimate of SNR
    andata(1:NT,nr,7) = squeeze(mean(std(reshape(cdata(stdWin(1):stdWin(2)-1,:,:),stdEachWin,7,NT),1,1),2));
    % Compute RC Value on each trial
    andata(1:NT,nr,8) = 1/-50*1000*(mean(cdata(rcwin(1):rcwin(2),:,1))-mean(cdata(rcBase(1):rcBase(2),:),1));
    
    for nt = 1:NT
        [~,cposidx] = max(cshd(positiveWin(1):positiveWin(2),nt));
        cposidx = cposidx + positiveWin(1) - 1;
        andata(nt,nr,4) = mean(cshd(cposidx-pkHalfWidth:cposidx+pkHalfWidth,nt));
        andataExtra(nt,nr,1) = cposidx;
        
        [~,cnegidx] = min(cshd(cposidx:cposidx+negWindow,nt));
        cnegidx = cnegidx + cposidx - 1;
        cnegvalue = mean(cshd(cnegidx-pkHalfWidth:cnegidx+pkHalfWidth,nt));
        andata(nt,nr,5) = cnegvalue;
        andataExtra(nt,nr,2) = cnegidx;
        
        fmValue = pkFractionMax*(andata(nt,nr,4)-andata(nt,nr,1)) + andata(nt,nr,1);
        riseIdx = find(cshd(cposidx:-1:1,nt)<=fmValue,1);
        fallIdx = find(cshd(cposidx:end,nt)<=fmValue,1);
        andata(nt,nr,10) = (riseIdx+fallIdx-2) * 0.01;
    end
    
    sdata = pall{nr}{1,2,2}; % soma data
    andata(1:NT,nr,6) = mean(sdata(preBaseWin(1):preBaseWin(2),:),1);
    
    % SNR
    andata(1:NT,nr,9) = (andata(1:NT,nr,4)-andata(1:NT,nr,1))./andata(1:NT,nr,7);
end

bswin = [find(tv>=80,1) find(tv>=98,1)];
bcAP = mean(cAP(bswin(1):bswin(2),:),1);
beAP = mean(eAP(bswin(1):bswin(2),:),1);
dcap = cAP - bcAP;
deap = eAP - beAP;
dap = deap - dcap;


% measure peaks with only best half of snrs...
snrDAP = zeros(size(dap));
snrEAP = zeros(size(pkEAP));
checkNum = zeros(NR,2);
for nr = 1:NR
    NT = size(pall{nr}{1,2,1},2);
    cpeak = andata(1:NT,nr,4)-andata(1:NT,nr,1);
    csnr = andata(1:NT,nr,9);
    idxThreshold = csnr>=prctile(csnr,50);
    %idxThreshold = cpeak>=prctile(cpeak,30);
    snrEAP(nr) = mean(cpeak(idxThreshold));
    checkNum(nr,1) = sum(idxThreshold);
    checkNum(nr,2) = NT;
    
    snrDAP(:,nr) = mean(pall{nr}{1,2,1}(:,idxThreshold),2) - mean(pall{nr}{1,1,1},2);
end
bsSnrDAP = mean(snrDAP(bswin(1):bswin(2),:),1);
bsnrDAP = snrDAP - bsSnrDAP;

% bootstrap analysis of slope
dmat = [ones(NR,1),pkImap(:)];
regressVals = dmat\(1000*snrEAP(:));
trueSlope = regressVals(2);

dmatRev = [ones(NR,1),1000*snrEAP(:)];
regressValsRev = dmatRev \ pkImap(:);

NR = numel(pkImap);
NB = 100000;
slope = zeros(1,NB);
for nb = 1:NB
    rv = [ones(NR,1),pkImap(randperm(NR))'] \ (1000*snrEAP(:));
    slope(nb) = rv(2);
end

[V,Edg] = histcounts(slope,1000);
idxTrueBin = find(Edg<trueSlope,1,'last');
pValue = sum(V(idxTrueBin+1:end))/sum(V);

% shift data based on peak time of dendritic recording 
smoothWindow = 10;
pkwin = [100 112];
pkidx = [find(tv>=pkwin(1),1), find(tv>=pkwin(2),1)];
[~,pktime] = max(smoothsmooth(bsnrDAP(pkidx(1):pkidx(2),:),smoothWindow),[],1);
[~,pkTimeSortIdx] = sort(pktime); % get sorting idx
bsnrDapShift = nan(size(bsnrDAP));
for nr = 1:NR
    bsnrDapShift(:,nr) = nanshift(bsnrDAP(:,nr),-pktime(nr));
end

[~,pkSortIdx] = sort(snrEAP);



% Figure 4D
idxExample = [12 11]; % idx in sres for 210212c, (referenced to metaKeep!) % 11 is silent, 12 is active
ptvIdx = find(tv>=75,1):find(tv>=350,1);
itvIdx = find(imtv>=75,1):find(imtv>=350,1);
ptvUse = tv(ptvIdx);
itvUse = imtv(itvIdx);
insetIdx = find(tv>=98,1):find(tv>=110,1);
insetUse = tv(insetIdx);
ixScale = 12; % 8
iyScale = 0.75; % 0.7
ixTrans = @(x) x*ixScale - 1040; % 665
iyTrans = @(y) y*iyScale;
iyShift = [3, 0.23]; % 3, 0.27
xLim = [75 300];
sap1 = medfilt1(sap(:,idxExample(1)),12);
sap2 = medfilt1(sap(:,idxExample(2)),12);
figure(4); clf; hold on;
set(gcf,'units','centimeters','position',[45 30 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.05 0.05 axWidth*0.92 axHeight*0.95]); % Note difference for equal axes!
plot(itvUse, bimap(itvIdx,idxExample(1)), 'color','k','linewidth',lineWidth);
plot(itvUse, bimap(itvIdx,idxExample(2)), 'color','b','linewidth',lineWidth);
xlim(xLim);
ylim([-0.07 0.355]);
% Mark AP Time
line([100 100],[-0.05 -0.025],'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [270 0.2 24 0.03];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d ms',scalePosition(3)),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),[sprintf('%d%%',100*scalePosition(4)),' \DeltaG/R'],'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');

% Figure 4E
figure(5); clf; hold on; 
set(gcf,'units','centimeters','position',[45 23.5 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.05 0.05 axWidth*0.92 axHeight*0.95]); % Note difference for equal axes!
patch([98 98 110 110],[-0.2 1 1 -0.2],'k','EdgeColor','None','FaceAlpha',0.1);
plot(ptvUse, bsnrDAP(ptvIdx,idxExample(1)), 'color','k','linewidth',lineWidth);
plot(ptvUse, bsnrDAP(ptvIdx,idxExample(2)), 'color','b','linewidth',lineWidth);
plot(ixTrans(insetUse), iyShift(2)+iyTrans(bsnrDAP(insetIdx,idxExample(1))), 'color','k','linewidth',lineWidth);
plot(ixTrans(insetUse), iyShift(2)+iyTrans(bsnrDAP(insetIdx,idxExample(2))), 'color','b','linewidth',lineWidth);
xlim(xLim);
ylim([-0.2 0.92]);
% Mark AP Time
line([100 100],[-0.2 -0.125],'color','k','linewidth',lineWidth);
line(ixTrans([100 100]),iyShift(2)+iyTrans([-0.17 -0.105]),'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [270 0.25 24 0.09];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d/%d ms',scalePosition(3)*[1 1/ixScale]),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),sprintf('%d/%d µV',1000*scalePosition(4)*[1 1/iyScale]),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');

% Figure 4F
figure(6); clf; hold on;
set(gcf,'units','centimeters','position',[45 17 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.05 0.05 axWidth*0.92 axHeight*0.95]); % Note difference for equal axes!
patch([98 98 110 110],[-98 45 45 -98],'k','EdgeColor','None','FaceAlpha',0.1);
plot(ptvUse, sap1(ptvIdx), 'color','k','linewidth',lineWidth);
plot(ptvUse, sap2(ptvIdx), 'color','b','linewidth',lineWidth);
plot(ixTrans(insetUse), iyShift(1)+iyTrans(sap1(insetIdx)), 'color','k','linewidth',lineWidth);
plot(ixTrans(insetUse), iyShift(1)+iyTrans(sap2(insetIdx)), 'color','b','linewidth',lineWidth);
xlim(xLim);
ylim([-98 45]);
% Mark AP Time
line([100 100],[-98 -90],'color','k','linewidth',lineWidth);
line(ixTrans([100 100]),iyShift(1)+iyTrans([-98 -90]),'color','k','linewidth',lineWidth);
% Scale Bar
scalePosition = [270 -55 24 9];
line(scalePosition(1)+[0 scalePosition(3)],scalePosition(2)*[1,1],'linewidth',lineWidth,'color','k');
line(scalePosition(1)*[1,1],scalePosition(2)+[0 scalePosition(4)],'linewidth',lineWidth,'color','k');
text(scalePosition(1),scalePosition(2),sprintf('%d/%d ms',scalePosition(3)*[1 1/ixScale]),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Top');
text(scalePosition(1),scalePosition(2),sprintf('%d/%d mV',scalePosition(4)*[1 1/iyScale]),'Fontsize',fontSize,'HorizontalAlignment','Left','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');



% Figure 4G
ptvIdx = find(tv>=75,1):find(tv>=350,1);
itvIdx = find(imtv>=75,1):find(imtv>=350,1);
ptvUse = tv(ptvIdx);
itvUse = imtv(itvIdx);
insetIdx = find(tv>=98,1):find(tv>=110,1);
insetUse = tv(insetIdx);
ixScale = 12; % 8
iyScale = 0.75; % 0.7
ixTrans = @(x) x*ixScale - 1040; % 665
iyTrans = @(y) y*iyScale;
iyShift = [3, 0.23]; % 3, 0.27
xLim = [75 300];
yLim = [-0.2 0.92];
idxSilent = pkImap <= 0.04;
idxActive = (pkImap >= 0.1) & (pkImap <= 0.3);
smoothing = [1 1];
bimapActive = smoothsmooth(bimap(:,idxActive),smoothing(1));
bimapSilent = smoothsmooth(bimap(:,idxSilent),smoothing(1));
bsnrActive = smoothsmooth(bsnrDAP(:,idxActive),smoothing(2));
bsnrSilent = smoothsmooth(bsnrDAP(:,idxSilent),smoothing(2));
figure(7); clf; hold on;
set(gcf,'units','centimeters','position',[50 30 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.05 0.05 axWidth*0.92 axHeight*0.95]); % Note difference for equal axes!
shadedErrorBar(itvUse, mean(bimapActive(itvIdx,:),2),std(bimapActive(itvIdx,:),1,2),{'color','k','linewidth',lineWidth},0);
shadedErrorBar(itvUse, mean(bimapSilent(itvIdx,:),2),std(bimapActive(itvIdx,:),1,2),{'color','b','linewidth',lineWidth},0);
xlim(xLim);
ylim([-0.07 0.355]);
% Mark AP Time
line([100 100],[-0.05 -0.025],'color','k','linewidth',lineWidth);
set(gca,'visible','off');

% Figure 4H
figure(8); clf; hold on;
set(gcf,'units','centimeters','position',[50 23.5 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.05 0.05 axWidth*0.92 axHeight*0.95]); % Note difference for equal axes!
patch([98 98 110 110],[-0.2 1 1 -0.2],'k','EdgeColor','None','FaceAlpha',0.1);
shadedErrorBar(ptvUse, mean(bsnrActive(ptvIdx,:),2),std(bsnrActive(ptvIdx,:),1,2)/sqrt(sum(idxActive)),{'color','k','linewidth',lineWidth},0);
shadedErrorBar(ptvUse, mean(bsnrSilent(ptvIdx,:),2),std(bsnrSilent(ptvIdx,:),1,2)/sqrt(sum(idxSilent)),{'color','b','linewidth',lineWidth},0);
shadedErrorBar(ixTrans(insetUse), iyShift(2)+iyTrans(mean(bsnrActive(insetIdx,:),2)),iyTrans(std(bsnrActive(insetIdx,:),1,2)/sqrt(sum(idxActive))),{'color','k','linewidth',lineWidth},0);
shadedErrorBar(ixTrans(insetUse), iyShift(2)+iyTrans(mean(bsnrSilent(insetIdx,:),2)),iyTrans(std(bsnrSilent(insetIdx,:),1,2)/sqrt(sum(idxSilent))),{'color','b','linewidth',lineWidth},0);
xlim(xLim);
ylim(yLim);
% Mark AP Time
line([100 100],[-0.2 -0.125],'color','k','linewidth',lineWidth);
line(ixTrans([100 100]),iyShift(2)+iyTrans([-0.12 -0.055]),'color','k','linewidth',lineWidth);
set(gca,'visible','off');



% Figure 4I
setBackX = [-0.05 -0.1 -0.07 -0.475];
setBackY = [-0.015 -0.028 -0.032 -0.07];
yLim = [0 2];
figure(9); clf; hold on;
set(gcf,'units','centimeters','position',[50 17 axWidth axHeight]);
set(gca,'units','centimeters','position',[0.45 0.65 axWidth*0.8 axHeight*0.61]); % Note difference for equal axes!
patch([0 0.04 0.04 0],[0 0 2 2],'b','FaceColor','b','FaceAlpha',0.2,'EdgeColor','none');
patch([0.1 0.3 0.3 0.1],[0 0 2 2],'k','FaceColor','k','FaceAlpha',0.2,'EdgeColor','none');
plot(pkImap, snrEAP,'marker','.','color','k','linestyle','none','markersize',markerSize);

xlim([setBackY(2) 0.45]);
ylim([setBackX(2) 2]);
line([0 0.45],setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],[0 2],'color','k','linewidth',lineWidth);
xticks = 0:0.2:0.4;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(0.225, setBackX(4), '\DeltaCa_{AP} (\DeltaG/R)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:2;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), 1, '\DeltamV','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');












%% -- Figure 4 - figure supplement 1 --


% Figure 4 - figure supplement 1A
saxWidth =colWidCM(3)/4;
saxHeight= colWidCM(3)/4*axAspectRatio;
setBackX = [-0.05 -0.1 -0.07 -0.25]/2*2;
setBackY = [-0.015 -0.03 -0.036 -0.135]/0.45*20/40*50;
xLim = [0 50];
yLim = [0 2];
figure(1); clf; hold on;
set(gcf,'units','centimeters','position',[42 30 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.7 0.55 saxWidth*0.775 saxHeight*0.775]); % Note difference for equal axes!
plot(resexp,snrEAP,'marker','.','color','k','linestyle','none','markersize',markerSize);
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(xLim,setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],yLim,'color','k','linewidth',lineWidth);
xticks = 0:10:50;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(mean(xLim), setBackX(4), 'Patch Resistance (M\Omega)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.5:2;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), 1, 'Dendritic Signal \DeltamV','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');


% Figure 4 - figure supplement 1B
setBackX = [-0.05 -0.1 -0.07 -0.25]/2*2;
setBackY = [-0.015 -0.03 -0.036 -0.135]/0.45*20;
xLim = [0 40];
yLim = [0 2];
figure(2); clf; hold on;
set(gcf,'units','centimeters','position',[47 30 saxWidth saxHeight]);
set(gca,'units','centimeters','position',[0.7 0.55 saxWidth*0.775 saxHeight*0.775]); % Note difference for equal axes!
plot(resexp-resctl,snrEAP,'marker','.','color','k','linestyle','none','markersize',markerSize);
xlim([setBackY(2) xLim(2)]);
ylim([setBackX(2) yLim(2)]);
line(xLim,setBackX(1)*[1,1],'color','k','linewidth',lineWidth);
line(setBackY(1)*[1,1],yLim,'color','k','linewidth',lineWidth);
xticks = 0:10:40;
for xt = xticks
    line(xt*[1,1],setBackX([1 2]),'color','k','linewidth',lineWidth);
    text(xt,setBackX(3),num2str(xt),'Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
end
text(mean(xLim), setBackX(4), 'Seal Resistance (M\Omega)','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Top');
yticks = 0:0.5:2;
for yt = yticks
    line(setBackY([1 2]),yt*[1,1],'color','k','linewidth',lineWidth);
    text(setBackY(3),yt,num2str(yt),'Fontsize',fontSize,'HorizontalAlignment','Right','VerticalAlignment','Middle');
end
text(setBackY(4), 1, 'Dendritic Signal \DeltamV','Fontsize',fontSize,'HorizontalAlignment','Center','VerticalAlignment','Bottom','Rotation',90);
set(gca,'visible','off');






